package com.itic.market.mobile.jd;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.market.mobile.jd.MallJdUtils;
import com.itic.market.mobile.base.BaseMobileInterface;
import com.itic.market.mobile.sharevo.ImgWordVo;
import com.itic.market.mobile.sharevo.UrlVo;
import com.itic.market.system.categoryjd.persistence.model.CategoryJd;
import com.itic.market.system.categoryjd.persistence.model.CategoryJdExample;
import com.itic.market.system.categoryjd.service.CategoryJdService;
import com.itic.market.system.marketuserproduct.persistence.model.MarketUserProduct;
import com.itic.market.system.marketuserproduct.persistence.model.MarketUserProductExample;
import com.itic.market.system.marketuserproduct.service.MarketUserProductService;
import com.itic.market.system.productjd.persistence.model.ProductJd;
import com.itic.market.system.productjd.persistence.model.ProductJdExample;
import com.itic.market.system.productjd.persistence.model.ProductJdExample.Criteria;
import com.itic.market.system.productjd.service.ProductJdService;
import com.itic.market.system.user.persistence.model.MarketUser;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.request.cps.ServicePromotionCouponGetCodeByUnionIdRequest;
import com.jd.open.api.sdk.response.cps.ServicePromotionCouponGetCodeByUnionIdResponse;

/**
 * 友惠家京东商城接口类
 * 
 * @author 徐泽威 2017年08月17日 14时11分
 */
@Controller
@RequestMapping(value = "/mobile/jd")
public class MarketJdInterface extends BaseMobileInterface {
    @Autowired 
    private ProductJdService productJdService;
    
    @Autowired
    private MarketUserProductService marketUserProductService;
    
    @Autowired 
    private CategoryJdService categoryJdService;
    
    
    
    @RequestMapping(value = "/pac")
    @ResponseBody
    public Map<String, Object> pac(HttpServletRequest requestest, HttpServletResponse responsetest ) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = FAIL;
        String errorCode = PARAM_ERROR_CODE;
        String errorMsg = PARAM_ERROR_MSG;
        try {
        	Document doc = Jsoup.connect("https://media.jd.com/").get();
        	Elements newsHeadlines = doc.select("#mp-itn b a");
        	for (Element headline : newsHeadlines) {
        	  String attr = headline.attr("title");
        	  String absUrl = headline.absUrl("href");
        	  System.out.println(attr+absUrl);
        	}
        	
        	//resultMap.put(DATA, response);
        	
            result = SUCCESS;
            errorCode = SUCCESS_ERROR_CODE;
            errorMsg = SUCCESS_ERROR_MSG;
        	
        } catch (Exception e) {
            errorCode = SERVER_ERROR_CODE;
            errorMsg = SERVER_ERROR_MSG;

        }
        resultMap.put(RESULT, result);
        resultMap.put(ERROR_CODE, errorCode);
        resultMap.put(ERROR_MSG, errorMsg);
        isCrrossDomain(responsetest);
        return resultMap;
    }
    
    
    /**
     * APP用户登入京东商城首页
     * 
     *  public JdClient client=new DefaultJdClient(SERVER_URL,accessToken,appKey,appSecret);

		ServicePromotionCouponGetCodeByUnionIdRequest request=new ServicePromotionCouponGetCodeByUnionIdRequest();
		
		request.setCouponUrl( "jingdong,yanfa,pop" );
		request.setMaterialIds( "jingdong,yanfa,pop" );
		request.setUnionId( 123 );
		request.setPositionId( 123 );
		
		ServicePromotionCouponGetCodeByUnionIdResponse response=client.execute(request);
     * 
     * @return
     */
    @RequestMapping(value = "/test")
    @ResponseBody
    public Map<String, Object> test(HttpServletRequest requestest, HttpServletResponse responsetest ) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = FAIL;
        String errorCode = PARAM_ERROR_CODE;
        String errorMsg = PARAM_ERROR_MSG;
        try {
        	String url = MallJdConfig.getUrl();//搜索有效商品信息
        	String accessToken = sysSettingService.getByKey("JD_ACCESS_TOKEN");//京东TOKEN
        	String appKey = MallJdConfig.getKey();
        	String appSecret = MallJdConfig.getSecret();
        	
        	//JdClient client=new DefaultJdClient(url,access_token,app_key,app_secret); 
        	//WareReadSearchWare4ValidRequest requestjd=new WareReadSearchWare4ValidRequest();
        	
        	
            JdClient client=new DefaultJdClient(url,accessToken,appKey,appSecret); 
            ServicePromotionCouponGetCodeByUnionIdRequest request=new ServicePromotionCouponGetCodeByUnionIdRequest();
            request.setCouponUrl( "http://item.jd.com/4714334.html" );
            request.setMaterialIds( "4714334" );
            request.setUnionId( 1000169071 );
            request.setPositionId( 1113711606 );
            ServicePromotionCouponGetCodeByUnionIdResponse response=client.execute(request);
            
        	/*UnionThemeGoodsServiceQueryCouponGoodsRequest request=new UnionThemeGoodsServiceQueryCouponGoodsRequest();
        	request.setFrom( 0 );
        	request.setPageSize( 1 );
        	//request.setCid3( 123 );
        	UnionThemeGoodsServiceQueryCouponGoodsResponse response=client.execute(request);*/
        	
        	String code = response.getCode();
        	if( "0".equals(code) ){
        		String msg = response.getMsg();
        		JsonParser parse =new JsonParser();  //创建json解析器
        		JsonElement parse2 = parse.parse(msg);
        		
        		//将msg转成
        		System.out.println(msg);
        	}else{
        		//同步失败
        	}
        	resultMap.put(DATA, response);
        	
            result = SUCCESS;
            errorCode = SUCCESS_ERROR_CODE;
            errorMsg = SUCCESS_ERROR_MSG;
        	
        } catch (Exception e) {
            errorCode = SERVER_ERROR_CODE;
            errorMsg = SERVER_ERROR_MSG;

        }
        resultMap.put(RESULT, result);
        resultMap.put(ERROR_CODE, errorCode);
        resultMap.put(ERROR_MSG, errorMsg);
        isCrrossDomain(responsetest);
        return resultMap;
    }
    

    /**
     * APP用户登入京东商城首页
     * 
     * @return
     */
    @RequestMapping(value = "/index")
    @ResponseBody
    public Map<String, Object> index(HttpServletRequest request, HttpServletResponse response, String keyword, String categoryId,String orderType,String minMaxPrice,String minMaxSales) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = FAIL;
        String errorCode = PARAM_ERROR_CODE;
        String errorMsg = PARAM_ERROR_MSG;
        try {
        	Map<String, Object> dataMap = new HashMap<String, Object>();
        	//获取京东商品信息
            ProductJdExample example = new ProductJdExample();
            //example.setOrderByClause("REORDER ASC");
            if( StringHelper.isNotBlank(orderType) ){
    			if( "priceDesc".equals(orderType) ){
    				example.setOrderByClause("CON_PRICE DESC");
    			}
    			if( "priceAsc".equals(orderType) ){
    				example.setOrderByClause("CON_PRICE ASC");
    			}
    			if( "commissionAsc".equals(orderType) ){
    				example.setOrderByClause("COMMISSION_PROFIT DESC");
    			}
    			if( "commissionDesc".equals(orderType) ){
    				example.setOrderByClause("COMMISSION_PROFIT ASC");
    			}
    		}else{
    			//默认使用商品的创建时间倒序
    			//example.setOrderByClause("REORDER ASC");
    		    example.setOrderByClause("UPDATE_TIME DESC");
    		    example.setOrderByClause("REORDER ASC");
    		}
            example.setOrderByClause("CON_URL_B DESC");
            
            Criteria criteria = example.createCriteria();
            
            criteria.andIsEffectiveEqualTo(DBConst.TRUE);
            if( StringHelper.isNotBlank(keyword) ){
            	 criteria.andGoodsNameLike("%" + keyword + "%");
            }
            if( StringHelper.isNotBlank(categoryId) && !"0".equals(categoryId) ){
            	CategoryJd categoryJd = categoryJdService.get(categoryId);
            	if( null != categoryJd ){
            		criteria.andCategoryNameLike("%"+ categoryJd.getName() +"%");
            	}
            }
            
            //过滤价格区间
        	if( StringHelper.isNotBlank(minMaxPrice) ){
        		String[] split = minMaxPrice.split("-");
        		if(split.length==2){
        			String minPrice = split[0];
            		String maxPrice = split[1];
            		if( StringHelper.isNotBlank(minPrice) ){
            			criteria.andOriPriceGreaterThanOrEqualTo(Double.parseDouble(minPrice));
            		}
            		if( StringHelper.isNotBlank(maxPrice) ){
            			criteria.andOriPriceLessThanOrEqualTo(Double.parseDouble(maxPrice));
            		}
        		}
        	}
        	this.handlePageQueryDefault(request, example);
            int count = productJdService.count(example);
            List<ProductJd> productJds = productJdService.list(example);
            
            dataMap.put("list", productJds);
            //dataMap.put("isMore", isMore(count,request));
            dataMap.put("totalRecords", count);
            resultMap.put(DATA, dataMap);
            result = SUCCESS;
            errorCode = SUCCESS_ERROR_CODE;
            errorMsg = SUCCESS_ERROR_MSG;
        	
        } catch (Exception e) {
            errorCode = SERVER_ERROR_CODE;
            errorMsg = SERVER_ERROR_MSG;

        }
        resultMap.put(RESULT, result);
        resultMap.put(ERROR_CODE, errorCode);
        resultMap.put(ERROR_MSG, errorMsg);
        isCrrossDomain(response);
        return resultMap;
    }
    
    /**
     * APP用户登入京东商城首页
     * 
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request, HttpServletResponse response, String keyword, String categoryId,String orderType,String minMaxPrice,String minMaxSales) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = FAIL;
        String errorCode = PARAM_ERROR_CODE;
        String errorMsg = PARAM_ERROR_MSG;
        try {
        	Map<String, Object> dataMap = new HashMap<String, Object>();
        	//获取京东商品信息
            ProductJdExample example = new ProductJdExample();
            //example.setOrderByClause("REORDER ASC");
            if( StringHelper.isNotBlank(orderType) ){
    			if( "priceDesc".equals(orderType) ){
    				example.setOrderByClause("CON_PRICE DESC");
    			}
    			if( "priceAsc".equals(orderType) ){
    				example.setOrderByClause("CON_PRICE ASC");
    			}
    		}else{
    			//默认使用商品的创建时间倒序
    			//example.setOrderByClause("REORDER ASC");
    		    example.setOrderByClause("UPDATE_TIME DESC");
    		    example.setOrderByClause("REORDER ASC");
    		}
            example.setOrderByClause("CON_URL_B DESC");
            
            Criteria criteria = example.createCriteria();
            
            criteria.andIsEffectiveEqualTo(DBConst.TRUE);
            if( StringHelper.isNotBlank(keyword) ){
            	 criteria.andGoodsNameLike("%" + keyword + "%");
            }
            if( StringHelper.isNotBlank(categoryId) && !"0".equals(categoryId) ){
            	CategoryJd categoryJd = categoryJdService.get(categoryId);
            	if( null != categoryJd ){
            		criteria.andCategoryNameLike("%"+ categoryJd.getName() +"%");
            	}
            }
            
            //过滤价格区间
        	if( StringHelper.isNotBlank(minMaxPrice) ){
        		String[] split = minMaxPrice.split("-");
        		if(split.length==2){
        			String minPrice = split[0];
            		String maxPrice = split[1];
            		if( StringHelper.isNotBlank(minPrice) ){
            			criteria.andOriPriceGreaterThanOrEqualTo(Double.parseDouble(minPrice));
            		}
            		if( StringHelper.isNotBlank(maxPrice) ){
            			criteria.andOriPriceLessThanOrEqualTo(Double.parseDouble(maxPrice));
            		}
        		}
        	}
        	this.handlePageQueryDefault(request, example);
            int count = productJdService.count(example);
            List<ProductJd> productJds = productJdService.list(example);
            
            dataMap.put("list", productJds);
            //dataMap.put("isMore", isMore(count,request));
            dataMap.put("totalRecords", count);
            resultMap.put(DATA, dataMap);
            result = SUCCESS;
            errorCode = SUCCESS_ERROR_CODE;
            errorMsg = SUCCESS_ERROR_MSG;
        	
        } catch (Exception e) {
            errorCode = SERVER_ERROR_CODE;
            errorMsg = SERVER_ERROR_MSG;

        }
        resultMap.put(RESULT, result);
        resultMap.put(ERROR_CODE, errorCode);
        resultMap.put(ERROR_MSG, errorMsg);
        isCrrossDomain(response);
        return resultMap;
    }
    
    
    /**
     * 获取二合一的地址
     * 
     * @return
     */
	@RequestMapping(value = "/convert")
    @ResponseBody
    public Map<String,Object> convert( HttpServletRequest request, HttpServletResponse response, String token, String id ){
    	Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = FAIL;
        String errorCode = PARAM_ERROR_CODE;
        String errorMsg = PARAM_ERROR_MSG;
        try {

            MarketUser user = getMarketUserByToken(token);
            if (null != user) {
            	ProductJd productJd2 = productJdService.get(id);
            	if( null != productJd2 ){
            		
            		String pid = getTgwidByUserid(user.getId());
					String convertResult = getConUrl(pid, productJd2.getSku(), productJd2.getConUrlB());
					if( StringHelper.isBlank(convertResult) ){
						convertResult = getCommonUrl(pid, productJd2.getSku());
					}
					resultMap.put(DATA, convertResult );
                    result = SUCCESS;
                    errorCode = SUCCESS_ERROR_CODE;
                    errorMsg = SUCCESS_ERROR_MSG;
            		
            	}else{
                    result = FAIL;
                    errorCode = JD_PRODUCT_EXPIRED_ERROR_CODE;
                    errorMsg = JD_PRODUCT_EXPIRED_ERROR_MSG;
            	}
            } else {
                result = LOGIN;
                errorCode = LOGIN_ERROR_CODE;
                errorMsg = LOGIN_ERROR_MSG;
            }
        
        } catch (Exception e) {
            errorCode = SERVER_ERROR_CODE;
            errorMsg = SERVER_ERROR_MSG;
            // log(e);
            // logException("MallJdInterface", "convert", e.toString(), "转成url链接", e);
        }
        resultMap.put(RESULT, result);
        resultMap.put(ERROR_CODE, errorCode);
        resultMap.put(ERROR_MSG, errorMsg);
        isCrrossDomain(response);
        return resultMap;
    }
    
	/**
     * 
     * @return
     */
    @RequestMapping(value = "/preShare")
    @ResponseBody
	public Map<String,Object> preShare( HttpServletRequest request, HttpServletResponse response, String token, String id ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(id) ){
    			MarketUser user = getMarketUserByToken(token);
    			//验证用户TOKEN
    			if( null != user ){
	    				Map<String, Object> dataMap = new HashMap<String,Object>();
	    				ProductJd productJd = productJdService.get(id);
	    				if( null != productJd ){
	    					//获得长链接
	    					//String convertResult = MallJdUtils.convert(user.getId(), productJd.getSku(), productJd.getConUrlB() );
	    					//jdCountStatics(user.getId(), convertResult, productJd.getSku(),"云店主获取二合一的地址分享");
	    					String pid = getTgwidByUserid(user.getId());
	    					String convertResult = getConUrl(pid, productJd.getSku(), productJd.getConUrlB());
	    					if( StringHelper.isBlank(convertResult) ){
	    						convertResult = getCommonUrl(pid, productJd.getSku());
	    					}
	    					if( StringHelper.isNotBlank(convertResult) ){
	    						String marketUserProductId = "";
	    						//判断用户的商品有没有，有就返回存在的
	        					MarketUserProductExample example = new MarketUserProductExample();
	        					com.itic.market.system.marketuserproduct.persistence.model.MarketUserProductExample.Criteria criteria = example.createCriteria();
	        					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	        					criteria.andUserIdEqualTo(user.getId());
	        					criteria.andProductIdEqualTo(id);
	        					List<MarketUserProduct> list = marketUserProductService.list(example);
	        					if( list.size() > 0 ){
	        						marketUserProductId = list.get(0).getId();
	        						result = SUCCESS;
	        						errorCode = SUCCESS_ERROR_CODE;
	                	        	errorMsg = SUCCESS_ERROR_MSG; 
	        					}else{
	        						marketUserProductId = IdGen.uuid();
	        						
	            					MarketUserProduct marketUserProduct = new MarketUserProduct();
	            					marketUserProduct.setId(marketUserProductId);
	                				//关联字段
	                				marketUserProduct.setUserId(user.getId());
	                				marketUserProduct.setProductId(id);
	                				//业务字段
	                				//marketUserProduct.setCategoryId(product.getCategoryId());
	                				marketUserProduct.setName(productJd.getGoodsName());
	                				marketUserProduct.setProductOrginPrice( Double.parseDouble(productJd.getOriPrice()) );
	                				marketUserProduct.setProductHongbao( Double.parseDouble(productJd.getConTicketPrice()) );
	                				marketUserProduct.setProductPrice( Double.parseDouble(productJd.getConPrice()) );
	                				marketUserProduct.setMarketProfit( productJd.getCommissionProfit() );
	                				marketUserProduct.setMarketProfitPercent(productJd.getCommission());
	                				marketUserProduct.setTotalSales( Integer.parseInt(RandomStringHelper.randomNumStr(3)) );
	                				marketUserProduct.setMainImageUrl(productJd.getGoodsUrl());
	                				marketUserProduct.setProfit("0");
	                				marketUserProduct.setProductType("002");
	                				marketUserProductService.add(marketUserProduct);
	        					}
	        					
	        					dataMap.put("preMoney", productJd.getCommissionProfit() );//预计收益多少钱
	        					//三种分享方式 
	        					//图文分享
	        					ImgWordVo imgWord = new ImgWordVo();
	        					imgWord.setImage(productJd.getGoodsUrl());
	        					imgWord.setWord(productJd.getGoodsName()+"\n" +
	        							  "----------------------\n" + 
					                      "京东价：" + productJd.getOriPrice() + "元\n" +
							              "券后价：" + productJd.getConPrice() + "元\n" +
					                      "----------------------\n" + convertResult);
	        					dataMap.put( "imageWord" , imgWord );
	        					//图片海报分享
	        					//String url = "http://file.jhjvip.cn:8082/mall/mobile/image/mergeJd?spuId=" + productJd.getId() + "&marketUserProductId="+ marketUserProductId +"&yunId="+user.getId();
	        					
	        					String url = getPoster(productJd.getGoodsName(), productJd.getGoodsUrl(), productJd.getOriPrice(), productJd.getConPrice(), productJd.getConTicketPrice() , productJd.getTotalSales(), "jd", convertResult);
	        					dataMap.put("image", url);
	        					//链接分享
	        					UrlVo urlVo = new UrlVo();
	        					urlVo.setImgUrl(productJd.getGoodsUrl());
	        					urlVo.setTitle("【领券更便宜】"+productJd.getGoodsName());
	        					urlVo.setContent("原价"+productJd.getOriPrice()+"元,券后价"+productJd.getConPrice()+"元,京东商城，正品保证。" );
	        					urlVo.setUrl(convertResult);
	        					dataMap.put("url", urlVo);
	        					
	        					resultMap.put(DATA, dataMap );
	        					result = SUCCESS;
	                            errorCode = SUCCESS_ERROR_CODE;
	                            errorMsg = SUCCESS_ERROR_MSG;
	    					}else{
	    						ProductJd temp = new ProductJd();
	    						temp.setId(id);
	                       	    productJdService.delete(temp);
	    						result = FAIL;
	                            errorCode = JD_PRODUCT_EXPIRED_ERROR_CODE;
	                            errorMsg = JD_PRODUCT_EXPIRED_ERROR_MSG;
	    					}
	    				}else{
	    					result = FAIL;
	                        errorCode = JD_PRODUCT_EXPIRED_ERROR_CODE;
	                        errorMsg = JD_PRODUCT_EXPIRED_ERROR_MSG;
	    				}
    				
    				}else{
    					result = LOGIN;
    					errorCode = LOGIN_ERROR_CODE;
    					errorMsg = LOGIN_ERROR_MSG; 
    				}
    			}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE; 
        	errorMsg = SERVER_ERROR_MSG;
        	e.printStackTrace();
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/share")
    @ResponseBody
    public Map<String, Object> share( HttpServletRequest request, HttpServletResponse response, String token, String id ){
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(id) ){
    			MarketUser user = getMarketUserByToken(token);
    			//验证用户TOKEN
    			if( null != user ){
	    				Map<String, Object> dataMap = new HashMap<String,Object>();
	    				ProductJd productJd = productJdService.get(id);
	    				if( null != productJd ){
	    					//获得长链接
	    					
	    					String convertResult = getConUrl(getTgwidByUserid(user.getId()), productJd.getSku(), productJd.getConUrlB());
	    					if( StringHelper.isNotBlank(convertResult) ){
	    						//判断用户的商品有没有，有就返回存在的
	        					MarketUserProductExample example = new MarketUserProductExample();
	        					com.itic.market.system.marketuserproduct.persistence.model.MarketUserProductExample.Criteria criteria = example.createCriteria();
	        					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	        					criteria.andUserIdEqualTo(user.getId());
	        					criteria.andProductIdEqualTo(id);
	        					List<MarketUserProduct> list = marketUserProductService.list(example);
	        					if( list.size() > 0 ){
	        						
	        						result = SUCCESS;
	        						errorCode = SUCCESS_ERROR_CODE;
	                	        	errorMsg = SUCCESS_ERROR_MSG; 
	        					}else{
	        						String marketUserProductId = IdGen.uuid();
	        						
	            					MarketUserProduct marketUserProduct = new MarketUserProduct();
	            					marketUserProduct.setId(marketUserProductId);
	                				//关联字段
	                				marketUserProduct.setUserId(user.getId());
	                				marketUserProduct.setProductId(id);
	                				//业务字段
	                				//marketUserProduct.setCategoryId(product.getCategoryId());
	                				marketUserProduct.setName(productJd.getGoodsName());
	                				marketUserProduct.setProductOrginPrice( Double.parseDouble(productJd.getOriPrice()) );
	                				marketUserProduct.setProductHongbao( Double.parseDouble(productJd.getConTicketPrice()) );
	                				marketUserProduct.setProductPrice( Double.parseDouble(productJd.getConPrice()) );
	                				marketUserProduct.setMarketProfit( productJd.getCommissionProfit() );
	                				marketUserProduct.setMarketProfitPercent(productJd.getCommission());
	                				marketUserProduct.setTotalSales( Integer.parseInt(RandomStringHelper.randomNumStr(3)) );
	                				marketUserProduct.setMainImageUrl(productJd.getGoodsUrl());
	                				marketUserProduct.setProfit("0");
	                				marketUserProduct.setProductType("002");
	                				marketUserProductService.add(marketUserProduct);
	        					}
	        					
	    						dataMap.put("url", convertResult );
	        					
	        					dataMap.put("imgUrl", productJd.getGoodsUrl());
	        					//String title = sysSettingService.getByKey("SHARE_TITLE");
	        					//dataMap.put("title", title==null?"友惠家商城":title);
	        					//dataMap.put("title", product.getName());
	        					//dataMap.put("title", user.getUserNickName()+"发来了一个"+  +"红包，赶快来领取吧");
	        					dataMap.put("title", "【领卷更便宜】"+productJd.getGoodsName());
	        					dataMap.put("content", "原价"+productJd.getOriPrice()+"元,券后价"+productJd.getConPrice()+"元,京东商城，正品保证。" );
	        					resultMap.put(DATA, dataMap );
	        					result = SUCCESS;
	                            errorCode = SUCCESS_ERROR_CODE;
	                            errorMsg = SUCCESS_ERROR_MSG;
	    					}else{
	    						ProductJd temp = new ProductJd();
	    						temp.setId(id);
	                       	    productJdService.delete(temp);
	    						result = FAIL;
	                            errorCode = JD_PRODUCT_EXPIRED_ERROR_CODE;
	                            errorMsg = JD_PRODUCT_EXPIRED_ERROR_MSG;
	    					}
	    					
	    				}else{
	    					result = FAIL;
	                        errorCode = JD_PRODUCT_EXPIRED_ERROR_CODE;
	                        errorMsg = JD_PRODUCT_EXPIRED_ERROR_MSG;
	    				}
    				
    				}else{
    					result = LOGIN;
    					errorCode = LOGIN_ERROR_CODE;
    					errorMsg = LOGIN_ERROR_MSG; 
    				}
    			}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE; 
        	errorMsg = SERVER_ERROR_MSG;
        	e.printStackTrace();
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/shareNew")
    @ResponseBody
    public Map<String, Object> shareNew( HttpServletRequest request, HttpServletResponse response, String token, String id ){
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(id) ){
    			MarketUser user = getMarketUserByToken(token);
    			//验证用户TOKEN
    			if( null != user ){
	    				Map<String, Object> dataMap = new HashMap<String,Object>();
	    				ProductJd productJd = productJdService.get(id);
	    				if( null != productJd ){
	    					//获得长链接
	    					
	    					//String convertResult = MallJdUtils.convert(user.getId(), productJd.getSku(), productJd.getConUrlB() );
	    					String convertResult = getConUrl(getTgwidByUserid(user.getId()), productJd.getSku(), productJd.getConUrlB());
	    					//jdCountStatics(user.getId(), convertResult, productJd.getSku(),"云店主获取二合一的地址分享");
	    					if( StringHelper.isNotBlank(convertResult) ){
	    						//判断用户的商品有没有，有就返回存在的
	        					MarketUserProductExample example = new MarketUserProductExample();
	        					com.itic.market.system.marketuserproduct.persistence.model.MarketUserProductExample.Criteria criteria = example.createCriteria();
	        					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	        					criteria.andUserIdEqualTo(user.getId());
	        					criteria.andProductIdEqualTo(id);
	        					List<MarketUserProduct> list = marketUserProductService.list(example);
	        					if( list.size() > 0 ){
	        						result = SUCCESS;
	        						errorCode = SUCCESS_ERROR_CODE;
	                	        	errorMsg = SUCCESS_ERROR_MSG; 
	        					}else{
	        						String marketUserProductId = IdGen.uuid();
	        						
	            					MarketUserProduct marketUserProduct = new MarketUserProduct();
	            					marketUserProduct.setId(marketUserProductId);
	                				//关联字段
	                				marketUserProduct.setUserId(user.getId());
	                				marketUserProduct.setProductId(id);
	                				//业务字段
	                				//marketUserProduct.setCategoryId(product.getCategoryId());
	                				marketUserProduct.setName(productJd.getGoodsName());
	                				marketUserProduct.setProductOrginPrice( Double.parseDouble(productJd.getOriPrice()) );
	                				marketUserProduct.setProductHongbao( Double.parseDouble(productJd.getConTicketPrice()) );
	                				marketUserProduct.setProductPrice( Double.parseDouble(productJd.getConPrice()) );
	                				marketUserProduct.setMarketProfit( productJd.getCommissionProfit() );
	                				marketUserProduct.setMarketProfitPercent(productJd.getCommission());
	                				marketUserProduct.setTotalSales( Integer.parseInt(RandomStringHelper.randomNumStr(3)) );
	                				marketUserProduct.setMainImageUrl(productJd.getGoodsUrl());
	                				marketUserProduct.setProfit("0");
	                				marketUserProduct.setProductType("002");
	                				marketUserProductService.add(marketUserProduct);
	        					}
	        					
	    						dataMap.put("url", convertResult );
	        					
	        					dataMap.put("imgUrl", sysSettingService.getByKey("MARKET_HONGBAO_URL"));
	        					//String title = sysSettingService.getByKey("SHARE_TITLE");
	        					//dataMap.put("title", title==null?"友惠家商城":title);
	        					//dataMap.put("title", product.getName());
	        					//dataMap.put("title", user.getUserNickName()+"发来了一个"+  +"红包，赶快来领取吧");
	        					dataMap.put("title", productJd.getGoodsName());
	        					dataMap.put("content", productJd.getGoodsName()+"\n" +
	        							  "----------------------\n" + 
					                      "京东价：" + productJd.getOriPrice() + "\n" +
							              "券后价：" + productJd.getConPrice() + "\n" +
					                      "----------------------\n" + convertResult);
	        					resultMap.put(DATA, dataMap );
	        					result = SUCCESS;
	                            errorCode = SUCCESS_ERROR_CODE;
	                            errorMsg = SUCCESS_ERROR_MSG;
	    					}else{
	    						ProductJd temp = new ProductJd();
	    						temp.setId(id);
	                       	    productJdService.delete(temp);
	    						result = FAIL;
	                            errorCode = JD_PRODUCT_EXPIRED_ERROR_CODE;
	                            errorMsg = JD_PRODUCT_EXPIRED_ERROR_MSG;
	    					}
	    					
	    				}else{
	    					result = FAIL;
	                        errorCode = JD_PRODUCT_EXPIRED_ERROR_CODE;
	                        errorMsg = JD_PRODUCT_EXPIRED_ERROR_MSG;
	    				}
    				
    				}else{
    					result = LOGIN;
    					errorCode = LOGIN_ERROR_CODE;
    					errorMsg = LOGIN_ERROR_MSG; 
    				}
    			}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE; 
        	errorMsg = SERVER_ERROR_MSG;
        	e.printStackTrace();
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    
    /**
     * APP用户登入商城中心首页
     * @return
     */
    @RequestMapping(value="/categorys")
    @ResponseBody
    public Map<String,Object> categorys(HttpServletRequest request,HttpServletResponse response){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//获取轮播图信息
    		CategoryJdExample example = new CategoryJdExample();
    		example.setOrderByClause("REORDER ASC");
    		example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
    		
            List<CategoryJd> list = categoryJdService.list(example);
            
            resultMap.put(DATA, list);
			result = SUCCESS;
			errorCode = SUCCESS_ERROR_CODE;
        	errorMsg = SUCCESS_ERROR_MSG;  
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
    		//logException("MallIndexInterface", "index", e.toString(),"登入商城中心首页",e);
		
    	}
    	resultMap.put(RESULT, result); 
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    /**
     * APP用户登入商城中心首页
     * @return
     */
    @RequestMapping(value="/sendBatch")
    @ResponseBody
    public Map<String,Object> sendBatch( HttpServletRequest request,HttpServletResponse response, String token , String ids ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(ids) && StringHelper.isNotBlank(token)){
    			MarketUser user = getMarketUserByToken(token);
    			if( null != user ){
    				List<MarketUserProduct> userProducts = new ArrayList<MarketUserProduct>();
    				List<String> list = new ArrayList<String>();
    				String[] jdss = ids.split(",");
    				if( jdss.length>0 ){
    					for( int i=0; i<jdss.length; i++ ){
        					ProductJd productJd = productJdService.get(jdss[i]);
        					//判断能否生成二合一链接
        					if( null != productJd  ){

    							//WeixinVo batch = new WeixinVo();
            					//判断用户的商品有没有，有就返回存在的
            					MarketUserProductExample example = new MarketUserProductExample();
            					com.itic.market.system.marketuserproduct.persistence.model.MarketUserProductExample.Criteria criteria = example.createCriteria();
            					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
            					criteria.andUserIdEqualTo(user.getId());
            					criteria.andProductIdEqualTo(jdss[i]);
            					List<MarketUserProduct> ttmp = marketUserProductService.list(example);
            					if( ttmp.size() > 0 ){
            						String qcUrl = getConUrl(getTgwidByUserid(user.getId()), productJd.getSku(), productJd.getConUrlB());
            						String imageUrl = getPoster(productJd.getGoodsName(), productJd.getGoodsUrl(), productJd.getOriPrice(), productJd.getConPrice(), productJd.getConTicketPrice() , productJd.getTotalSales(), "jd", qcUrl);
            						list.add( imageUrl );
            					}else{
            						
            						String marketUserProductId = IdGen.uuid();
                					MarketUserProduct marketUserProduct = new MarketUserProduct();
                					marketUserProduct.setId(marketUserProductId);
                					marketUserProduct.setOrgCode(ORG_CODE);
                					marketUserProduct.setCreateTime(new Date());
                					marketUserProduct.setUpdateTime(new Date());
                					marketUserProduct.setIsEffective(DBConst.TRUE);
                					marketUserProduct.setCreateUser(CREATE_USER);
                    				//关联字段
                    				marketUserProduct.setUserId(user.getId());
                    				marketUserProduct.setProductId(productJd.getId());
                    				//业务字段
                    				marketUserProduct.setCategoryId(productJd.getCategoryName());
                    				marketUserProduct.setName(productJd.getGoodsName());
                    				marketUserProduct.setProductOrginPrice(Double.parseDouble(productJd.getOriPrice()));
                    				marketUserProduct.setProductHongbao(Double.parseDouble(productJd.getConTicketPrice()));
                    				marketUserProduct.setProductPrice(Double.parseDouble(productJd.getConPrice()));
                    				marketUserProduct.setMarketProfit(productJd.getCommissionProfit());
                    				marketUserProduct.setMarketProfitPercent(productJd.getCommission());
                    				marketUserProduct.setTotalSales(Integer.parseInt(RandomStringHelper.randomNumStr(3)));
                    				marketUserProduct.setMainImageUrl(productJd.getGoodsUrl());
                    				marketUserProduct.setProfit("0");
                    				marketUserProduct.setProductType("002");
            						userProducts.add(marketUserProduct);
            						String qcUrl = getConUrl(getTgwidByUserid(user.getId()), productJd.getSku(), productJd.getConUrlB());
            						String imageUrl = getPoster(productJd.getGoodsName(), productJd.getGoodsUrl(), productJd.getOriPrice(), productJd.getConPrice(), productJd.getConTicketPrice() , productJd.getTotalSales(), "jd", qcUrl);
            						list.add( imageUrl ); 
            					}
        					}
        				}
    				}
    			 	result = marketUserProductService.addBatch(userProducts);
        			resultMap.put(DATA,list);
    				result = SUCCESS;
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG;  
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  
    			}
    			
    		}
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
    		//logException("MallIndexInterface", "index", e.toString(),"登入商城中心首页",e);
		
    	}
    	resultMap.put(RESULT, result); 
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
     
    
}